<?php

class Application_Model_ProductMapper {
	
	protected $_dbTable;
	
	public function setDbTable($dbTable){
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable(){
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Product');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Product $product){
		$data = array(
				'id_category'   => $product->getId_category(),
				'name' => $product->getName(),
				'picture_location' => $product->getPicture_location(),
				'price' => $product->getPrice(),
				'nbr_pieces' => $product->getNbr_pieces(),
		);
	
		if (null === ($id = $product->getId())) {
			unset($data['id_product']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_product = ?' => $id));
		}
	}
	
	public function find($id, Application_Model_Product $product){
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$product->setId($id)
			->setId_category($row->id_category)
			->setName($row->name)
			->setPicture_location($row->picture_location)
			->setPrice($row->price)
			->setNbr_pieces($row->nbr_pieces);
	}
	
	public function fetchAll() {
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Product();
			$entry->setId($row->id_product)
				->setId_category($row->id_category)
				->setName($row->name)
				->setPicture_location($row->picture_location)
				->setPrice($row->price)
				->setNbr_pieces($row->nbr_pieces);
			$entries[] = $entry;
		}
		return $entries;
	}
	
	public function delete($id){
		$where = $this->getDbTable()->getAdapter()->quoteInto('id_product = ?', $id);
		return $this->getDbTable()->delete($where);
	}
	
	public function fetchAllWithIds($productIds){
		$resultSet = $this->getDbTable()->fetchAll(" id_product IN(".implode(",", $productIds).")", "id_product");
		
		$entries = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Product();
			$entry->setId($row->id_product)
			->setId_category($row->id_category)
			->setName($row->name)
			->setPicture_location($row->picture_location)
			->setPrice($row->price)
			->setNbr_pieces($row->nbr_pieces);
			$entries[] = $entry;
		}
		return $entries;
	}
	
	public function decreaseStock($id_product){
		$where = $this->getDbTable()->getAdapter()->quoteInto('id_product = ?', $id);
		$data = array("nbr_pieces" => "nbr_pieces-1");
		$this->getDbTable()->update($data, $where);
	}
}

